<template>
  <div class="common-layout">
    <el-container class="frame-container">
      <el-header class="frame-header">
        <el-menu
            :default-active="activeIndex"
            class="header-menu"
            mode="horizontal"
            :ellipsis="false"
            @select="headerMenuSelect"
        >
          <el-menu-item index="0" class="home-logo">
            <img
                src="@/assets/image/logo-green.svg"
                alt="AMAT logo"
                @click="goHome"
            />
          </el-menu-item>
          <el-menu-item index="1">about</el-menu-item>
          <el-sub-menu index="2">
            <template #title>admin</template>
            <el-menu-item index="2-1">个人中心</el-menu-item>
            <el-menu-item index="2-2">重置密码</el-menu-item>
            <el-menu-item index="2-3">退出登录</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>
      <el-container>
        <el-aside width="auto">
          <el-button-group size="small">
            <el-button
                type="primary"
                @click="toggleCollapse"
                style="margin-bottom: 20px"
                :icon="isCollapse ? ArrowRight : ArrowLeft"
            >{{ isCollapse ? '展开' : '收起' }}
            </el-button>
          </el-button-group>
          <el-menu
              :default-active="menuPath"
              class="el-menu-vertical-demo"
              :collapse="isCollapse"
              @open="asideMenuOpen"
              @close="asideMenuClose"
              @select="asideMenuSelect"
              router

          >
            <!--            <MenuItem :myRoute="availableRoutes"/>-->
            <MenuItem v-for="route in avaAllRoutes" :myRoute="route"/>
          </el-menu>
        </el-aside>
        <el-container>
          <el-main>
            <el-tabs
                v-model="activeTab"
                type="card"
                closable
                addable
                class="demo-tabs"
                @tab-remove="removeTab"
                @tab-click="clickTab"
                router
            >
              <template #add-icon>
                <el-button @click="closeAllTabs" type="info" size="small">
                  关闭所有
                </el-button>

                <el-icon>
                  <CloseBold/>
                </el-icon>
              </template>
              <el-tab-pane
                  v-for="item in tabs"
                  :key="item.name"
                  :label="item.title"
                  :name="item.name"
                  :closable="item.closable"
                  :lazy="true"
              >

              </el-tab-pane>
            </el-tabs>
            <!--            <router-view/>-->
            <router-view/>
          </el-main>
          <el-footer class="home-footer">amat-1.0.0.1</el-footer>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>


<script setup lang="ts">
import {computed, onMounted, ref, watch} from 'vue'
import {ArrowLeft, ArrowRight, CloseBold,} from '@element-plus/icons-vue'
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import MenuItem from "@/components/MenuItem.vue";
import {allRoutes} from "@/router";
import {showMsg, ShowType} from "@/plugin/message.ts";

const router = useRouter();
const route = useRoute()

const isCollapse = ref(false) // 侧边栏是否折叠
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value; // 切换状态
}; // 侧边栏折叠与展开
const activeIndex = ref('1') // 当前激活的菜单
const availableRoutes = router.getRoutes().filter((arr) => {
  return arr.meta.isShow
}) // 获取路由

const menuPath = ref(route.path)
const activeTab = ref('') // 当前激活的标签页
const tabs = ref<[]>([])  // tab标签页列表
const headerMenuSelect = (key: string, keyPath: string) => {


}
const asideMenuOpen = (key: string, keyPath: string) => {


}
const asideMenuClose = (key: string, keyPath: string[]) => {

}

const asideMenuSelect = (index: string, keyPath: string) => {
  const targetRoute = availableRoutes.find((r) => r.path === index)
  if (targetRoute) {
    addTabFromRoute(targetRoute);
    router.push(index);
    menuPath.value = index
  }

};


// 点击Tab标签页
const clickTab = (tab) => {
  router.push({
    name: tab.props.name
  })
}

// 关闭Tab标签页
const removeTab = (targetName: string) => {
  if (targetName == "home") {
    showMsg(ShowType.Warning, '首页不可关闭!')
    return
  }
  const tempTabs = tabs.value
  let tempActive = activeTab.value
  if (activeTab.value === targetName) {
    tempTabs.forEach(
        (tab, index) => {

          if (tab.name === targetName) {
            const nextTab = tempTabs[index + 1] || tempTabs[index - 1]
            if (nextTab) {
              tempActive = nextTab.name
            }
          }


        }
    )

  }
  activeTab.value = tempActive;
  tabs.value = tempTabs.filter((tab) => tab.name !== targetName);

  store.dispatch("tabs/removeTab", targetName);

};
const closeAllTabs = () => {
  goHome()
}

// 根据路由动态添加标签页
const addTabFromRoute = (route: any) => {

  if (!tabs.value.some((tab) => tab.name === route.name)) {
    const newTab = {
      name: route.name,
      title: route.meta.title,
      closable: route.meta.closable ?? true,
    }
    tabs.value.push(newTab);
    store.dispatch("tabs/addTab", newTab)
  }
  activeTab.value = route.name;

};
watch(
    () => route.path,
    (newPath) => {
      // 路由变化时,
      menuPath.value = newPath;
      activeTab.value = route.name
    }
)

watch(
    () => activeTab.value, (newTab) => {
      // tab 变化时,更新路由
      router.push({
        name: newTab
      })

    }
)
// 初始化时，如果当前路径有对应的标签页，则添加
const store = useStore()

// 获取已打开的标签页
const openedTabs = computed(() => store.state.tabs.openedTabs)

// 页面加载时恢复 Tabs
store.dispatch('tabs/loadTabs');


onMounted(() => {
  store.dispatch('tabs/loadTabs'); // 加载 Tabs
  tabs.value = openedTabs.value
  if (route.name) {
    addTabFromRoute(route);

  }
});

const goHome = () => {
  router.push('/')
  store.dispatch('tabs/clearTabs')
  tabs.value = []

}


const avaAllRoutes = computed(() => {
  return allRoutes.filter(route => route.meta.isShow);
});

</script>


<style scoped>
.frame-container {
  height: 100vh;

  .frame-header {
    height: 40px;

    .header-menu {
      height: 40px;
    }
  }

  .home-footer {
    align-items: center;
    text-align: center;
  }
}


.home-logo img {
  width: 80px;
}

.el-menu--horizontal > .el-menu-item:nth-child(1) {
  margin-right: auto;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: auto;
  min-height: auto;
}
</style>